package com.information.service.impl;

import com.information.entity.User;
import com.information.repository.UserRepository;
import com.information.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StatisticsServiceImpl implements StatisticsService {

    private final UserRepository userRepository;

    @Autowired
    public StatisticsServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public Map<String, Object> getUserOverview() {
        Map<String, Object> overview = new HashMap<>();
        
        // 总用户数
        long totalUsers = userRepository.countByIsDeleteFalse();
        
        // 活跃用户数
        long activeUsers = userRepository.countByIsDeleteFalseAndStatus(User.UserStatus.ACTIVE);
        
        // 今日新增用户
        LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        long todayNewUsers = userRepository.countByIsDeleteFalseAndCreatedAtAfter(todayStart);
        
        // 本月新增用户
        LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
        long monthNewUsers = userRepository.countByIsDeleteFalseAndCreatedAtAfter(monthStart);
        
        overview.put("totalUsers", totalUsers);
        overview.put("activeUsers", activeUsers);
        overview.put("todayNewUsers", todayNewUsers);
        overview.put("monthNewUsers", monthNewUsers);
        
        return overview;
    }

    @Override
    public Map<String, Object> getRegionStatistics() {
        List<User> users = userRepository.findAllActiveUsers();
        
        Map<String, Long> regionCount = users.stream()
                .filter(user -> user.getAddress() != null && !user.getAddress().trim().isEmpty())
                .collect(Collectors.groupingBy(
                        user -> extractProvince(user.getAddress()),
                        Collectors.counting()
                ));
        
        // 转换为ECharts需要的格式
        List<Map<String, Object>> data = regionCount.entrySet().stream()
                .map(entry -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("name", entry.getKey());
                    item.put("value", entry.getValue());
                    return item;
                })
                .sorted((a, b) -> Long.compare((Long) b.get("value"), (Long) a.get("value")))
                .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("data", data);
        result.put("total", users.size());
        
        return result;
    }

    @Override
    public Map<String, Object> getAgeStatistics() {
        List<User> users = userRepository.findAllActiveUsers();
        
        Map<String, Long> ageGroups = users.stream()
                .filter(user -> user.getAge() != null && user.getAge() > 0)
                .collect(Collectors.groupingBy(
                        user -> getAgeGroup(user.getAge()),
                        Collectors.counting()
                ));
        
        // 确保所有年龄段都有数据
        String[] groups = {"18岁以下", "18-25岁", "26-35岁", "36-45岁", "46-55岁", "56岁以上"};
        List<String> categories = Arrays.asList(groups);
        List<Long> values = categories.stream()
                .map(group -> ageGroups.getOrDefault(group, 0L))
                .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("categories", categories);
        result.put("values", values);
        
        return result;
    }

    @Override
    public Map<String, Object> getStatusStatistics() {
        List<User> users = userRepository.findAllActiveUsers();
        
        Map<String, Long> statusCount = users.stream()
                .collect(Collectors.groupingBy(
                        user -> getStatusDisplayName(user.getStatus()),
                        Collectors.counting()
                ));
        
        List<Map<String, Object>> data = statusCount.entrySet().stream()
                .map(entry -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("name", entry.getKey());
                    item.put("value", entry.getValue());
                    return item;
                })
                .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("data", data);
        
        return result;
    }

    @Override
    public Map<String, Object> getGenderStatistics() {
        List<User> users = userRepository.findAllActiveUsers();
        
        Map<String, Long> genderCount = users.stream()
                .filter(user -> user.getGender() != null && !user.getGender().trim().isEmpty())
                .collect(Collectors.groupingBy(
                        User::getGender,
                        Collectors.counting()
                ));
        
        // 添加未知性别统计
        long unknownCount = users.stream()
                .filter(user -> user.getGender() == null || user.getGender().trim().isEmpty())
                .count();
        
        if (unknownCount > 0) {
            genderCount.put("未知", unknownCount);
        }
        
        List<Map<String, Object>> data = genderCount.entrySet().stream()
                .map(entry -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("name", entry.getKey());
                    item.put("value", entry.getValue());
                    return item;
                })
                .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("data", data);
        
        return result;
    }

    @Override
    public Map<String, Object> getRoleStatistics() {
        List<User> users = userRepository.findAllActiveUsers();
        
        Map<String, Long> roleCount = users.stream()
                .collect(Collectors.groupingBy(
                        user -> getRoleDisplayName(user.getRole()),
                        Collectors.counting()
                ));
        
        List<Map<String, Object>> data = roleCount.entrySet().stream()
                .map(entry -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("name", entry.getKey());
                    item.put("value", entry.getValue());
                    return item;
                })
                .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("data", data);
        
        return result;
    }

    @Override
    public Map<String, Object> getRegistrationTrend() {
        LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
        List<User> recentUsers = userRepository.findByIsDeleteFalseAndCreatedAtAfter(thirtyDaysAgo);
        
        Map<String, Long> dailyCount = recentUsers.stream()
                .collect(Collectors.groupingBy(
                        user -> user.getCreatedAt().toLocalDate().toString(),
                        Collectors.counting()
                ));
        
        // 生成最近30天的日期列表
        List<String> dates = new ArrayList<>();
        List<Long> counts = new ArrayList<>();
        
        for (int i = 29; i >= 0; i--) {
            String date = LocalDateTime.now().minusDays(i).toLocalDate().toString();
            dates.add(date);
            counts.add(dailyCount.getOrDefault(date, 0L));
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("dates", dates);
        result.put("counts", counts);
        
        return result;
    }

    // 辅助方法
    private String extractProvince(String address) {
        if (address == null || address.trim().isEmpty()) {
            return "未知";
        }
        
        // 简单的省份提取逻辑
        String[] provinces = {"北京", "上海", "天津", "重庆", "河北", "山西", "辽宁", "吉林", "黑龙江",
                "江苏", "浙江", "安徽", "福建", "江西", "山东", "河南", "湖北", "湖南", "广东",
                "海南", "四川", "贵州", "云南", "陕西", "甘肃", "青海", "台湾", "内蒙古", "广西",
                "西藏", "宁夏", "新疆", "香港", "澳门"};
        
        for (String province : provinces) {
            if (address.contains(province)) {
                return province;
            }
        }
        
        return "其他";
    }

    private String getAgeGroup(Integer age) {
        if (age < 18) return "18岁以下";
        if (age <= 25) return "18-25岁";
        if (age <= 35) return "26-35岁";
        if (age <= 45) return "36-45岁";
        if (age <= 55) return "46-55岁";
        return "56岁以上";
    }

    private String getStatusDisplayName(User.UserStatus status) {
        if (status == null) return "未知";
        switch (status) {
            case ACTIVE: return "激活";
            case INACTIVE: return "禁用";
            case LOCKED: return "锁定";
            default: return "未知";
        }
    }

    private String getRoleDisplayName(User.UserRole role) {
        if (role == null) return "未知";
        switch (role) {
            case SUPER_ADMIN: return "超级管理员";
            case ADMIN: return "管理员";
            case USER: return "普通用户";
            default: return "未知";
        }
    }
}